package com.wlb365.admin.modules.license.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlb365.admin.common.exception.AdminException;
import com.wlb365.admin.modules.license.entity.License;
import com.wlb365.admin.modules.license.mapper.LicenseMapper;
import com.wlb365.admin.modules.license.service.LicenseService;
import com.wlb365.admin.modules.schedule.utils.DateUtil;
import com.wlb365.license.client.LicenseEntity;
import com.wlb365.license.server.LicenseServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2020-06-24 09:11:14
 */
@Service
public class LicenseServiceImpl extends ServiceImpl<LicenseMapper, License> implements LicenseService {
    @Autowired
    private LicenseServer licenseServer;

    @Override
    public Page<License> listLicensePage(License license) {
        Page<License> page = new Page<>(license.getCurrent(), license.getSize());
        List<License> licenses = baseMapper.selectLicenseList(license, page);
        return page.setRecords(licenses);
    }

    @Override
    @Transactional
    public void generate(License license) {
        try {
            license.setStatus("0");
            this.save(license);

            Map<String, String> map = licenseServer.generate(license.getTime() + license.getUnit()
                    , license.getCode()
                    , "license_" + license.getId() + ".txt"
                    , "source_" + license.getId() + ".txt");
            license.setLicensePath(map.get("licensePath"));
            license.setSourcePath(map.get("sourcePath"));

            com.wlb365.license.client.License license1 = new com.wlb365.license.client.License();
            File file = new File(license.getLicensePath());
            LicenseEntity licenseEntity = license1.loadLicense(file);
            license.setApplyTime(DateUtil.getDateTimeOfTimestamp(licenseEntity.getApplyTime()));
            license.setExpireTime(DateUtil.getDateTimeOfTimestamp(licenseEntity.getExpireTime()));

            this.updateById(license);

        } catch (Exception e) {
            log.error("生成license文件失败", e);
            throw new AdminException("生成license文件失败");
        }


    }
}
